package com.eh.jedis;

import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import redis.clients.jedis.*;

import java.util.List;

/**
 * Created by David Li on 2016/5/9.
 */
@Service
public class RedisClientService {
    private static String Redis_Server_IP = "10.198.197.255";
    private static int Redis_Server_Port = 6379;

    private Jedis jedis; //非切片额客户端连接
    private JedisPool jedisPool; // 非切片连接池
    private ShardedJedis shardedJedis; // 切片额客户端连接
    private ShardedJedisPool shardedJedisPool; // 切片额连接池

    public RedisClientService() {
        initPool();
        jedis = jedisPool.getResource();
        initShardedPool();
        shardedJedis = shardedJedisPool.getResource();
    }

    /**
     * 初始化非切片池
     */
    private void initPool() {
        // 池基本配置
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(20);
        config.setMaxIdle(5);
        config.setMaxWaitMillis(10000);
        config.setTestOnBorrow(false);

        jedisPool = new JedisPool(config, Redis_Server_IP, Redis_Server_Port);
    }

    /**
     * 初始化切片池
     */
    private void initShardedPool() {
        // 池基本配置
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(2000);
        config.setMaxIdle(5);
        config.setMaxWaitMillis(10000);
        config.setTestOnBorrow(false);
        // slave连接
        List<JedisShardInfo> shardInfos = Lists.newArrayList();
        shardInfos.add(new JedisShardInfo(Redis_Server_IP, Redis_Server_Port, "master"));
        // 构造池
        shardedJedisPool = new ShardedJedisPool(config, shardInfos);
    }

    public Jedis getJedis() {
        return jedis;
    }

    public ShardedJedis getShardedJedis() {
        return shardedJedis;
    }
}
